package com.right.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.Tools.PageData;
import com.commons.AjaxResponse;
import com.google.gson.Gson;
import com.right.dao.StoreDao;
import com.right.dao.impl.StoreDaoImpl;
import com.right.entity.Store;
import com.right.service.StoreService;
import com.right.service.impl.StoreServiceImpl;




/**
 * Servlet implementation class StoreServlet
 */
@WebServlet("/StoreServlet")
public class StoreServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	StoreDao storedao = new StoreDaoImpl();
	StoreService storeservice = new StoreServiceImpl();

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		String op = "";
		if (request.getParameter("op") != null) {
			op = request.getParameter("op");
		}
		if ("add".equals(op)) {
			doAddStore(request, response);
		} else if ("update".equals(op)) {
			doUpdate(request, response);
		} else if ("selectByName".equals(op)) {
			doSelectByName(request, response);
		} else if ("selectByPage".equals(op)) {
			doSelectByPage(request, response);
		} else if ("login".equals(op)) {
			doLogin(request, response);
		}else if("ajaxstore".equals(op)) {
			doAjaxGetName(request, response);
		}else if ("".equals(op)) {
			response.sendRedirect("main.jsp");
		}else if ("delete".equals(op)) {
			doDelete(request, response);
		}
	}
	public void doDelete(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		int storeid = 0;
		if (request.getParameter("storeid") != null) {
			storeid = Integer.parseInt(request.getParameter("storeid"));

		}
		// 2调用 service的方法
		boolean flag = storeservice.delStore(storeid);
		AjaxResponse res = new AjaxResponse(flag + "", 200);
		// 3将list转为json格式的字符串
		Gson gson = new Gson();
		String jsonString = gson.toJson(res);
		// 4 响应
		PrintWriter outPrintWriter = response.getWriter();
		outPrintWriter.print(jsonString);
		// 关闭
		outPrintWriter.close();

	}
	
	public void doUpdate(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		int storeid = 0;
		if (request.getParameter("storeid") != null) {
			storeid = Integer.parseInt(request.getParameter("storeid"));
		}
		
		String store = request.getParameter("store");
		String storename = request.getParameter("storename");
		String storecall = request.getParameter("storecall");
		String address = request.getParameter("address");
		String storeinfo = request.getParameter("storeinfo");
		double money = Double.parseDouble(request.getParameter("money"));
		    Store st=new Store(storeid, store, storename, storecall, address, storeinfo, money);
             boolean flag=storeservice.updateStore2(st);        
             AjaxResponse res = new AjaxResponse(flag+"", 200);
 		    //3将list转为json格式的字符串
 		    Gson gson=new Gson();
 		    String jsonString=gson.toJson(res); 
 		    //4 响应
 		    PrintWriter outPrintWriter=response.getWriter();
 		    outPrintWriter.print(jsonString);
 		    //关闭
 		    outPrintWriter.close();
	}
	private void doAjaxGetName(HttpServletRequest request, HttpServletResponse response) throws IOException {
		// 1.设置响应头的contentType
		response.setContentType("application/json;charset=utf-8");
		String store = request.getParameter("store");
		System.out.println("store :"+store);
		// 2 调用 service的方法,查询是否存在store对象
		Store s = storeservice.getStoreByName(store);
		System.out.println(s);
		String msg = "类型名称存在，请换一个！";
		if (s==null) {
			//?没有找到
			msg="商店名称不存在,可以使用.";
		}
		// 3将msg转换为json格式的字符串
		Gson gson = new Gson();
		String jsonString = gson.toJson(msg);
		// 4 响应
		PrintWriter out = response.getWriter();
		out.print(jsonString);
		// 5.关闭
		out.close();
	}
	
	private void doAddStore(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		String store = request.getParameter("store");
		String storename = request.getParameter("storename");
		String storepwd = request.getParameter("storepwd");
		String storecall = request.getParameter("storecall");
		String address = request.getParameter("address");
		String storeinfo = request.getParameter("storeinfo");
		double money = 0;
		System.out.println(store+storename+storepwd+storecall+address+storeinfo);
		Store s = new Store(store, storename, storepwd, storecall, address, storeinfo, money);
		// 4.调用service
		boolean flag = storeservice.addStore(s);
		// 5.根据结果转跳页面
		if (flag) {
			response.sendRedirect("storelogin.jsp");
		} else {
			request.setAttribute("msg", "增加失败！请重新添加。");
			request.getRequestDispatcher("storeregister.jsp").forward(request, response);
		}
	}

	private void doSelectByName(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		String keywords = "";
		// 2获取请求参数
		if (request.getParameter("keywords") != null) {
			keywords = request.getParameter("keywords");
		}

		// 3 调用 dao的方法
		@SuppressWarnings("unchecked")
		List<Store> list = (List<Store>) storedao.getStoreByName(keywords);
		System.out.println(list.size());
		// 4传递list给jsp
		request.setAttribute("list", list);
		// 5 转发
		request.getRequestDispatcher("store.html").forward(request, response);
	}

	private void doSelectByPage(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		String keywords = "";
		// 2获取请求参数
		if (request.getParameter("keywords") != null) {
			keywords = request.getParameter("keywords");
		}
		// 页码默认为1
		int page = 1;
		// 每页记录默认为10
		int pageSize = 10;
		if (request.getParameter("page") != null) {
			page = Integer.parseInt(request.getParameter("page"));
		}
		if (request.getParameter("pageSize") != null) {
			pageSize = Integer.parseInt(request.getParameter("pageSize"));
		}
		// 3 调用 service的方法
		PageData<Store> pd = storeservice.getStoreByPage(page, pageSize, keywords);
		// 4传递pd给jsp
		request.setAttribute("pd", pd);
		// 传递模糊查询的字符串
		request.setAttribute("keywords", keywords);
		// 5转发
		request.getRequestDispatcher("adminstore.jsp").forward(request, response);
	}

	private void doLogin(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// 获取商家登录名和密码
		String storename = request.getParameter("storename");
		String storepwd = request.getParameter("storepwd");
		// 调用StoreDaoImpl对象的login方法登录验证
		boolean flag = storeservice.login(storename, storepwd);
		if (flag) {
			// 登录验证成功，传递商家登录名的值，并跳转到商家首页
			//request.setAttribute("storename", storename);
			//用户选择了记住密码
			if(request.getParameter("remember")!=null) {
				//创建cookie，并设置其过期时间，存储到本地
				Cookie cookie1 = new Cookie("storename", storename);
				cookie1.setMaxAge(60*60);//过期时间1h
				Cookie cookie2 = new Cookie("storepwd", storepwd);
				cookie2.setMaxAge(60*60);
				//将cookie的信息存储在本地: addCookie
				response.addCookie(cookie1);
				response.addCookie(cookie2);
			}
			Store store = storeservice.getStoreByLoginName(storename);
			HttpSession session = request.getSession();
			session.setAttribute("store",store);
			System.out.println(store);
			request.getRequestDispatcher("s-user.jsp").forward(request, response);
		} else {
			// 登录验证不成功，返回到登录界面
			request.setAttribute("msg", "密码错误，请输入正确密码");
			request.getRequestDispatcher("storelogin.jsp").forward(request, response);
		}
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}
